﻿// Created by: Jeff McKelvey
// Creation date: 3/6/2010
// Utility class introduced to replace the Microsoft.SPOT dependency

using System;

namespace Grommet.Ext
{
	public static class Utility
	{
		/// <summary>
		/// Combines all of the data fom two arrays of bytes into one array.
		/// This method combines two arrays by appending the second array at the end of the first array.
		/// </summary>
		/// <param name="src1"></param>
		/// <param name="src2"></param>
		/// <returns></returns>
		public static byte[] CombineArrays(byte[] src1, byte[] src2)
		{
			byte[] array = new byte[src1.Length + src2.Length];
			Array.Copy(src1, array, src1.Length);
			Array.Copy(src2, 0, array, src1.Length, src2.Length);
			return array;
		}

		/// <summary>
		/// Inserts a value at a specified position in a byte array.
		/// </summary>
		/// <param name="data">The array into which you want to insert the specified value.</param>
		/// <param name="pos">The position in the array where you want to insert the specified value.</param>
		/// <param name="size">The size of the data objects contained in the array, in bytes. Valid arguments for this parameter are 1, 2, and 4.</param>
		/// <param name="val">The value you want to insert into the array.</param>
		public static void InsertValueIntoArray(byte[] data, int pos, int size, UInt32 val)
		{
			byte[] valBytes;

            switch (size)
            {
                case 1:
                    valBytes = new byte[1];
                    valBytes[0] = (byte)val;
                    break;

                case 2:
                    valBytes = BigEndianConvert.GetBytes((ushort)val);
                    break;

                case 4:
                    valBytes = BigEndianConvert.GetBytes((int)val);
                    break;

                default:
                    throw new Exception(string.Format("InsertValueIntoArray: {0} is an invalid value for 'size' param.", size));
            }

			for (int i = 0; i < valBytes.Length; i++)
				data[i + pos] = valBytes[i];
		}

		/// <summary>
		/// Extracts a linear section of data from a byte array.
		/// </summary>
		/// <param name="data">The byte array of data.</param>
		/// <param name="offset">The offset from the beginning of the byte array to the target data.</param>
		/// <param name="count">The amount of data you want to extract, in bytes.</param>
		/// <returns></returns>
		public static byte[] ExtractRangeFromArray(byte[] data, int offset, int count)
		{
			byte[] array = new byte[count];

			for (int i = 0; i < count; i++)
				array[i] = data[i + offset];

			return array;
		}
	}
}
